package com.classtest.DemoExpend.controller;


import com.alibaba.fastjson.JSON;
import com.classtest.DemoExpend.bean.DbOrder;
import com.classtest.DemoExpend.bean.DbUser;
import com.classtest.DemoExpend.service.DbOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HomeOrderController {

    @Autowired
    DbOrderService dbOrderService;

    // 记录订单数量
    @RequestMapping("/homeOrder")
    public String homeOrder(HttpServletRequest request, DbOrder dbOrder) {
        DbUser user = (DbUser) request.getSession().getAttribute("user");
        dbOrder.setUsId(user.getId());
        List<DbOrder> userOrderCount = dbOrderService.getOrderCount(JSON.toJSONString(dbOrder));
        int orderCount = 0; // 记录该用户下的商品数量
        Map<String,Object> orderResult = new HashMap<>();
        for (DbOrder order:userOrderCount) {
            orderCount ++;
        }
        orderResult.put("orderCount",orderCount);
        return JSON.toJSONString(orderResult);
    }

    // 获取订单列表
    @RequestMapping("/orderAll")
    public String orderAll(HttpServletRequest request, DbOrder dbOrder){
        DbUser user = (DbUser) request.getSession().getAttribute("user");
        dbOrder.setUsId(user.getId());
        List<DbOrder> userOrderAll = dbOrderService.getOrderCount(JSON.toJSONString(dbOrder));
        Map<String,Object> orderAll = new HashMap<>();
        List<Object> list = new ArrayList<>();
        for (DbOrder order: userOrderAll){
            Map<String,Object> res = new HashMap<>();
            res.put("oid",order.getOid());
            res.put("buyId",order.getBuyerId());
            res.put("usId",order.getUsId());
            res.put("gsId",order.getGsId());
            res.put("buyTime",order.getBuyTime());
            res.put("total",order.getTotal());
            res.put("status",order.getStatus());
            res.put("address",order.getAddress());
            res.put("courierNum",order.getCourierNum());
            list.add(res);
        }
        orderAll.put("orders",list);
        return JSON.toJSONString(orderAll);
    }

    // 添加快递单号
    @RequestMapping("/addCourierNum")
    public String addCourierNum(@RequestBody String json) {
        Map<String,Object> addCourier = new HashMap<>();
        try {
            dbOrderService.updateCourierNum(json);
            addCourier.put("flag","ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(addCourier);
    }
}
